package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"management/database"
	cjwt "management/jwt"
	"management/util"
)

// 格式化token数据，获取用户信息
func parseToken(tokenString string, secretKey []byte) (*cjwt.MyCustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &cjwt.MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return secretKey, nil
	})

	if claims, ok := token.Claims.(*cjwt.MyCustomClaims); ok && token.Valid {
		return claims, nil
	} else {
		return nil, err
	}
}

// 验证token中间件
func AuthTokenMiddleware(secretKey []byte) gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.GetHeader("token")
		if len(tokenString) <= 0 {
			util.Error(c, &util.Result{Data: nil, Msg: "请登录后再操作！"})
			c.Abort()
			return
		}
		claims := &cjwt.MyCustomClaims{}
		// 验证token是否已经过期
		_, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
			return secretKey, nil
		})
		if err != nil {
			util.Error(c, &util.Result{Data: nil, Msg: "token无效"})
			c.Abort()
			return
		}
		// 获取用户信息，准备去数据库查询是否存在该用户
		userInfo, _ := parseToken(tokenString, secretKey)
		db, err := database.GetDBInstance()
		if err != nil {
			panic(err)
		}
		var users []database.User
		db.Table("user").Where("name = ? and id = ?", userInfo.UserName, userInfo.Id).Find(&users)
		if len(users) <= 0 {
			util.Error(c, &util.Result{Data: nil, Msg: "该用户不存在，无权访问！"})
			c.Abort()
			return
		}
		c.Next()
	}
}
